package com.tc.config.auth.server;

import com.tc.common.constant.SecurityConstants;
import com.tc.config.auth.server.service.impl.SpringDataUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @Auther: tianchao
 * @Date: 2020/5/16 15:44
 * @Description:
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;
    @Autowired
    private ClientDetailsService clientDetailsService;
    /**
     * 令牌存储策略
     */
    @Autowired
    private TokenStore tokenStore;
    /**
     * 配置客户端详情服务
     * @param clients
     * @throws Exception
     * 用来配置客户端详情服务(ClientDetailsService),客户端详情信息在这里进行初始化
     * 你能够把客户端信息写死在这里，或者通过数据库来存贮调取详情信息
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //使用内存来实现客户端详情服务
                .withClient("my_client_id") //标识客户的Id
                .secret(passwordEncoder().encode("my_client_secret")) //（需要值得信任的客户端）客户端安全码，如果有的话
                .authorizedGrantTypes(SecurityConstants.IMPLICIT,SecurityConstants.REFRESH_TOKEN, SecurityConstants.PASSWORD,SecurityConstants.AUTHORIZATION_CODE) //此客户端可以使用的授权类型
                .scopes("server")    //用来限制客户端的访问范围，如果为空（默认）的话，那么客户端拥有全部的访问范围
                //跳转到授权页面，让用户授权，是ture的话就直接默认同意了
                .autoApprove(true)
                .redirectUris("http://www.baidu.com");

    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 安全约束配置
     * 允许用户如何访问
     * @param security
     * @throws Exception
     * 配置令牌端点的安全约束
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //令牌端点 /oauth/token_key是公开
                .tokenKeyAccess("permitAll()")
                //用于资源服务访问的令牌解析端点/oauth/check_token 设置公开
                .checkTokenAccess("permitAll()")
                //表单认证
                .allowFormAuthenticationForClients()
        ;
    }
    /**
     * 令牌访问端点
     * @param endpoints
     * @throws Exception
     * 用来配置令牌(token)的访问端点和令牌服务(token service)
     */
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                //认证管理器 //针对密码模式
                .authenticationManager(authenticationManager)
                //授权码服务 //针对授权码模式
                .authorizationCodeServices(authorizationCodeServices)
                //令牌管理五福
                .tokenServices(tokenService())
                //.tokenStore(tokenStore)
                //.userDetailsService(userDetailsService)
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }


    /**
     * 设置授权码模式的授权码如何存取，暂时采用内存方式
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(){
        return new InMemoryAuthorizationCodeServices();
    }


    /**
     *令牌管理服务
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenService(){
        DefaultTokenServices service = new DefaultTokenServices();
        //客户端详情服务
        service.setClientDetailsService(clientDetailsService);
        //支持刷新令牌
        service.setSupportRefreshToken(true);
        //令牌存储
        service.setTokenStore(tokenStore);
        /**
         * jwt converter 设置进去 ，令牌增强
         */
       /* TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
        service.setTokenEnhancer(tokenEnhancerChain);*/
        //令牌默认有效期2小时
        service.setAccessTokenValiditySeconds(7200);
        //刷新令牌默认有效期2天
        service.setRefreshTokenValiditySeconds(259200);
        return service;
    }

}
